/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package swym.server;

import swym.protocol.*;
import swym.server.file.*;

import java.net.*;
import java.util.*;

/**
 *
 * @author mschaefer
 */
public class ClientConnection 
{
    /**
     * This class will represent the client connection with an address, port pair.
     * 
     * The client should be able to have many of these - allowing for client
     * connections at a time.
     */
    private InetAddress address;
    private int port;
    private boolean isConnected;
    private Client client;
    private boolean isUpdate;
    private ClientSocket socket;
    
    public ClientConnection( InetAddress address, int port )
    {
        this.address = address;
        this.port = port;
        
        isConnected = true;
        isUpdate = false;
    }
    
    public void setClient( Client client )
    {
        this.client = client;
    }
    
    public void setSocket( ClientSocket socket )
    {
        this.socket = socket;
    }
    
    /**
     * If this client connection is the one on which
     * the client should recieve updates, then set
     * this field to true (the default is false).
     * 
     * @param isUpdate
     */
    public void setIsUpdateConnection( boolean isUpdate )
    {
        this.isUpdate = isUpdate;
    }
    
    /**
     * Add a file action to the update queue - (eventually
     * to be sent to the client)
     * @param newAction
     */
    public void queueClientUpdate( FileAction newAction )
    {
        FileActionMessage message = new FileActionMessage( newAction.getFile().getOwner().getName(),
                                                           client.getName(), 
                                                           newAction.getType(),
                                                           0 );
        message.setFileInformation( newAction.getFile() );
        
        SocketOutputThread.getInstance().queueAction( this, socket, message );
    }
    
    public boolean isUpdateConnection() { return isUpdate; }
    
    public Client getClient() { return client; }
    
    public void disconnect()
    {
        if ( isConnected )
        {
            isConnected = false;

            if ( client != null )
                client.closeConnection( this );
        }
    }
    
    public boolean isConnected() { return isConnected; }
    
    public String toString()
    {
        return ( client != null ? client.toString() : ": " )
               + address.toString() + ":" + port;
    }
}
